/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useEffect, useState } from 'react';
import { ModalForm, ProFormRadio } from '@ant-design/pro-form';
import { openVip, getCardInfo } from '@/services/MiniAppManagement';
import { message } from 'antd';
import type { ProFormInstance } from '@ant-design/pro-form';
import { isArray } from 'lodash';

interface OpenModalProps {
  updateList?: () => void;
  onCancel: () => void;
  visible: boolean;
  listId: string;
  channel: string;
}

const OpenModal: React.FC<OpenModalProps> = ({
  channel,
  listId,
  visible,
  onCancel,
  updateList,
}) => {
  const formRef = useRef<ProFormInstance>();
  const [options, setOptions] = useState<
    {
      label: string;
      value: string;
    }[]
  >([]);

  const onOk = async (value: any) => {
    const { code, msg } = await openVip({ card_id: value.card_id, user_id: listId, channel });
    if (code == 0) {
      message.success(msg);
      if (updateList) {
        updateList();
      }
      if (onCancel) {
        formRef.current?.resetFields();
        onCancel();
      }
    } else {
      message.error(msg);
    }
  };

  const cancel = () => {
    formRef.current?.resetFields();
    onCancel();
  };

  useEffect(() => {
    if (visible) {
      getCardInfo({ user_id: listId }).then(({ code, data = [], msg }) => {
        if (code == 0) {
          if (isArray(data) && data.length > 0) {
            const arr = data.map((val) => ({
              label: val.name,
              value: val.id,
            }));

            setOptions(arr);
          }
        } else {
          message.error(msg);
        }
      });
    }
  }, [visible, listId]);

  return (
    <ModalForm
      formRef={formRef}
      width={260}
      title='开通会员类型'
      visible={visible}
      onFinish={onOk}
      modalProps={{
        centered: true,
        onCancel: cancel,
        okText: '确认开通',
        cancelText: '取消开通',
      }}
    >
      <ProFormRadio.Group
        name='card_id'
        options={options}
        rules={[
          {
            required: true,
            message: '请选择会员卡类型',
          },
        ]}
      />
    </ModalForm>
  );
};

export default OpenModal;
